#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sqlite3.h>

static void read_file(
  sqlite3_context *pCtx,
  int nVal,
  sqlite3_value **apVal
){
  int fd = 0;
  off_t rst;
  ssize_t sz;
  unsigned char buf[4096]={0,};
  const char *fPath = (const char*)sqlite3_value_text(apVal[0]);
  int pos = atoi((const char*)sqlite3_value_text(apVal[1]));
  int len = atoi((const char*)sqlite3_value_text(apVal[2]));
  sqlite3 *db = sqlite3_context_db_handle(pCtx);
  
  if( len>4096 ){
	printf("Read too long!!\n");
  }

  fd = open(fPath, O_RDONLY);
  if( fd<0 ){
	printf("Open file[%s] failed due to %d\n", fPath, errno);
  }
  
  rst = lseek(fd, pos, SEEK_SET);
  //printf("lseek() got %ld\n", rst);
  
  sz = read(fd, (void *)buf, len);
  //printf("read() got %ld bytes\n", sz);
  
  sqlite3_result_blob(pCtx, buf, len, SQLITE_TRANSIENT);
  //sqlite3_result_value(pCtx, apVal[0]);
}

int register_my_funcs(sqlite3 *db){
  sqlite3_create_function(db, "read_file", 3, SQLITE_UTF8, 0, read_file, 0, 0);
}